/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.CoursechapterauditlogQueryCriteria;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.modules.system.service.CoursechapterauditlogService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @description 服务实现
* @author shitou
* @date 2025-01-20
**/
@Service
@RequiredArgsConstructor
public class CoursechapterauditlogServiceImpl extends ServiceImpl<CoursechapterauditlogMapper, Coursechapterauditlog> implements CoursechapterauditlogService {

    private final CoursechapterauditlogMapper coursechapterauditlogMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    private final CoursechapterMapper coursechapterMapper;

    private final CourseMapper courseMapper;

    @Override
    public PageResult<Coursechapterauditlog> queryAll(CoursechapterauditlogQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(coursechapterauditlogMapper.findAll(criteria, page));
    }

    @Override
    public List<Coursechapterauditlog> queryAll(CoursechapterauditlogQueryCriteria criteria){
        return coursechapterauditlogMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Coursechapterauditlog resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        resources.setTeacherId(Math.toIntExact(teacher.getId()));
        save(resources);

        //获取所有章节状态
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("courseId",resources.getCourseId());
        queryWrapper1.eq("parentId",0);
        List<Coursechapter> coursechapterList = coursechapterMapper.selectList(queryWrapper1);
        Integer status = 0;
        List<Integer> coursechapterNum = new ArrayList<>();
        for(Coursechapter coursechapter:coursechapterList){
            if(coursechapter.getState() == 2){
                status = 1;
                coursechapterNum.add(1);
            }
        }

        if(coursechapterNum.size() == coursechapterList.size()){
            Course course = courseMapper.selectById(resources.getCourseId());
            course.setState2(2);
            courseMapper.updateById(course);
        } else {
//            if(status == 1){
                Course course = courseMapper.selectById(resources.getCourseId());
                course.setState2(1);
                courseMapper.updateById(course);
//            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Coursechapterauditlog resources) {
        Coursechapterauditlog coursechapterauditlog = getById(resources.getId());
        coursechapterauditlog.copy(resources);
        saveOrUpdate(coursechapterauditlog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Coursechapterauditlog> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Coursechapterauditlog coursechapterauditlog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" courseid",  coursechapterauditlog.getCourseId());
            map.put(" teacherid",  coursechapterauditlog.getTeacherId());
            map.put(" content",  coursechapterauditlog.getContent());
            map.put(" state",  coursechapterauditlog.getState());
            map.put(" createtime",  coursechapterauditlog.getCreateTime());
            map.put(" lastupdatetime",  coursechapterauditlog.getLastUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}